import re


class WordFilter:
    """
    单词过滤器: 替换掉字符串中的特定字符串为指定字符串, 并返回发生替换后的响应
    """

    def __init__(self, word_sub: dict, filter_response: str = None):
        """
        :param word_sub:需要替换的词=>替换后的词字典
        :param filter_response:如果发生替换, 则可立即返回
        """
        self.filter_response = filter_response
        self.word_sub = dict((re.escape(key), v) for key, v in word_sub.items())
        if '' in self.word_sub.keys():
            self.word_sub.pop('')
        s = r'|'.join(self.word_sub.keys())
        self.pattern = re.compile(s)
        # 在匹配时是否发生了替换
        self.has_replaced = False

    def filter(self, string: str):
        """
        替换指定字符串为其对应的字符串
        :param string:
        :return:
        """
        self.has_replaced = False

        def _word_sub_event(filtering_filter: WordFilter, x):
            """
            发生替换时的事件
            :param filtering_filter: 正在进行替换的过滤器
            :param x: 匹配的输入
            :return:
            """
            filtering_filter.has_replaced = True
            return filtering_filter.word_sub[re.escape(x.group(0))]

        # 如果发生了替换, 第二个返回值会是非None, 表示
        return self.pattern.sub(
            lambda x: _word_sub_event(self, x), string
        ).strip(), self.filter_response if self.has_replaced else None


if __name__ == "__main__":
    import os
    from const import RESOURCE_PATH

    rude_word = set()

    with open(os.path.join(RESOURCE_PATH, 'sensitiveness', 'keyword.txt'),
              encoding='utf-8') as file:
        for k in file.readlines():
            k = k.replace('\n', '').strip()
            if len(k) > 0:
                rude_word.add(k)

    clean_word = {'。', '.', '?', '？', '!', '，', ',', '嗯', '噫', '啊', '哦'}
    clean_dict = dict((k, '') for k in clean_word)
    rude_dict = dict((k, '*') for k in rude_word)
    clean_filter = WordFilter(clean_dict, 'clean response')
    rude_filter = WordFilter(rude_dict, 'rude response')
    text = '。dads.asfa?asdsad？!, 嗯?？'
    text, response = clean_filter.filter(text)
    print(text)
    print(response)
    text = '你真是个大傻逼大傻子傻大个大坏蛋坏人'
    text, response = clean_filter.filter(text)
    print(text)
    print(response)
    text = "你真是个大傻逼，大傻子，傻大个，大坏蛋，坏人。"
    text, response = rude_filter.filter(text)
    print(text)
    print(response)
